package com.ms.p2p.controller.app;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.exception.NoticeException;
import com.ms.common.mapper.JsonMapper;
import com.ms.common.utils.*;
import com.ms.p2p.Constants;

import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.RetMap;
import com.ms.p2p.entity.UserThreadLocal;
import com.ms.p2p.entity.account.AccountBank;
import com.ms.p2p.entity.content.Article;
import com.ms.p2p.entity.content.ArticleCategory;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.plugin.IPlugin;
import com.ms.p2p.plugin.payment.IPaymentEvent;
import com.ms.p2p.plugin.payment.PaymentPluginBundle;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import com.ms.p2p.service.PayMethodService;
import com.ms.p2p.service.PayMethodValueService;
import com.ms.p2p.service.RSAService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chensk on 2018/3/14.
 */
@Controller
@RequestMapping({ "/api" })
public class ApiIndexController extends  com.ms.p2p.controller.app.BaseController{

    @Reference
    private YeahpaysProvider yeahpaysProvider;
    @Reference
    private MemberProvider memberProvider;
    @Reference
    private MemberAccountProvider memberAccountProvider;

    @Reference
    private LoanTenderRecordProvider tenderService;
    @Reference
    private LoanCategoryProvider borrowTypeService;
    @Reference
    private SettingProvider settingProvider;
    @Reference
    private SendProvider smsService;
    @Autowired
    private RSAService rsaService;

    @Reference
    private ArticleCategoryProvider categoryProvider;

    @Reference
    private ArticleProvider articleProvider;

    @Reference
    private TestProvider testProvider;
    @Reference
    CertiFiCationProvider certificationProvider;

    @Reference
    private AdvertProvider advertProvider;

    @Autowired
    private ServletContext applicationScope;
    @Autowired
    public PayMethodService payMethodService;

    @Autowired
    public PayMethodValueService payMethodValueService;
    @Reference
    public FuyouProvider fuyouProvider;

    @Reference
    public LoanProvider loanProvider;
    @Reference
    public MemberAccountBankProvider accountBankProvider;

    @Autowired
    PaymentPluginBundle paymentPluginBundle;

    @Reference
    RedPacketCategoryProvider redPacketCategoryProvider;

    @Reference
    private ArticleCategoryProvider artileTypeProvider;


    /**
     * 找回(支付,交易)密码获取验证码
     */
    @RequestMapping("/findpassword/getRegCode")
    @ResponseBody
    public HashMap getRegCode(String mobile,  HttpServletResponse response) throws IOException, TemplateException {
        //发送校验


        Member user = memberProvider.findByMobilePhone(mobile);
        if(user==null){
            throw  new NoticeException("用户不存在");
        }
        Object mobileCodeSession =  applicationScope.getAttribute(user.getUser_name());
        if(mobileCodeSession!=null){
            String session1 = mobileCodeSession.toString();
            String[] codes = StringUtils.split(session1, "_");
            if(System.currentTimeMillis() - Long.valueOf(codes[1]) < 1000*10*6){
                throw  new NoticeException("60秒内只能发送一条短信");
            }
        }
        if(user==null){
            throw  new NoticeException("用户不存在");

        }

        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
        String mobileCode = CommonUtil.getRandomNum(6);
        String nickname = settingProvider.findByCode("email_from_name")
                .getText();
        String templatePath = Constants.TEMPLATE_SMS_BIND;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath, "utf-8");
        HashMap map = new HashMap();
        map.put("code",mobileCode);
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        // 发送短信
        smsService.sendSMS(mobile,"【"+nickname+"】"+content, "找回密码", 0);
        applicationScope.setAttribute(user.getUser_name(),mobileCode + "_" + System.currentTimeMillis());
        return RetMap.Success("发送短信成功");
    }

    /**
     * 修改登录密码
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "mobile", message = "手机验证码不能为空"),
            @RequiredStringValidator(fieldName = "code", message = "手机验证码不能为空"),
            @RequiredStringValidator(fieldName = "pass1", message = "就密码不能为空"),
            @RequiredStringValidator(fieldName = "pass2", message = "确认不能为空")
    })
    @RequestMapping("/modifyLoginPassword")
    @ResponseBody
    public HashMap modifyLoginPassword(String code,String mobile, String pass1, String pass2) {

        Member member =   memberProvider.findByMobilePhone(mobile);
        // 密码正则
        String pwdRegex = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,20}$";



        if (!StringUtils.equals(pass1, pass2)) {
            throw new NoticeException("两次输入的密码不一致！");
        }

        String mobileCodeSession;
        try {
           mobileCodeSession =  applicationScope.getAttribute(member.getUser_name()).toString();
        }catch (Exception e){
            throw new NoticeException("验证码错误或过期无效");
        }

        if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
            throw new NoticeException("验证码错误或过期无效");
        }
        //验证码验证
        String[] codes = StringUtils.split(mobileCodeSession, "_");
        if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10 || StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], code) ){
            throw new NoticeException("验证码错误或过期无效");
        }
        applicationScope.removeAttribute(member.getUser_name());
        member.setLogin_password(DigestUtils.md5Hex(pass1));
        member.setUp_time(String.valueOf(System.currentTimeMillis()));
        member.setUp_ip(AppContext.getRemoteIp());
        memberProvider.updateById(member);
        return RetMap.Success("密码重置成功！");
    }

    /**
     * 修改支付密码
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "mobile", message = "手机验证码不能为空"),
            @RequiredStringValidator(fieldName = "code", message = "手机验证码不能为空"),
            @RequiredStringValidator(fieldName = "pass1", message = "新密码不能为空"),
            @RequiredStringValidator(fieldName = "pass2", message = "确认密码不能为空")

    })
    @RequestMapping("/modifyPayPassword")
    @ResponseBody
    public HashMap modifyPayPwd(String mobile, String code,  String pass1, String pass2) {
        Member member =   memberProvider.findByMobilePhone(mobile);
        // 密码正则
        String pwdRegex = "^(.*){6,20}$";


        if (!StringUtils.equals(pass1, pass2)) {
            throw new NoticeException("两次输入的密码不一致！");
        }

        if (!pass1.matches(pwdRegex)) {
            throw new NoticeException("密码必须6-20位");
        }

        if (member.getLogin_password().equals(
                DigestUtils.md5Hex(pass1))) {
            throw new NoticeException("交易密码不能和登陆密码相同！");
        }

        String mobileCodeSession;
        try {
            mobileCodeSession =  applicationScope.getAttribute(member.getUser_name()).toString();
        }catch (Exception e){
            throw new NoticeException("验证码错误或过期无效");
        }
        if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
            throw new NoticeException("验证码错误或过期无效");
        }
        //验证码验证
        String[] codes = StringUtils.split(mobileCodeSession, "_");
        if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10 || StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], code) ){
            throw new NoticeException("验证码错误或过期无效");
        }

        applicationScope.removeAttribute(member.getUser_name());
        member.setPayment_password(DigestUtils.md5Hex(pass1));
        member.setUp_time(String.valueOf(System.currentTimeMillis()));
        member.setUp_ip(AppContext.getRemoteIp());
        memberProvider.updateById(member);

        return RetMap.Success("密码重置成功！");
    }




    /**
     * 获取
     */
    @RequestMapping({"/rookie"})
    public String rookie(HttpServletRequest request) {
        PageBean a =new PageBean();
        a.setPageSize(100);
        List<HashMap> redpacketCategorys= redPacketCategoryProvider.findPager(a);
        List<HashMap> newred = new ArrayList<HashMap>() ;

        for(HashMap redpacketCategory: redpacketCategorys){

            redpacketCategory.put("tender_time_limit",Integer.parseInt(redpacketCategory.get("tender_time_limit").toString())*30);

            if(redpacketCategory.get("is_disable").toString().equals("1")){

                newred.add(redpacketCategory);
            }
        }

       request.setAttribute("rookies",newred);
        return "/webview/rookie";
    }

    /**
     * 获取
     */
    @RequestMapping({"/article/list"})
    @ResponseBody
    //notice 关于我们activity 活动公告 新闻咨询intro
    public HashMap list(String cate_name,
                        @RequestParam(value = "currentPage", defaultValue = "1", required = false)
                       Integer currentPage, Model model) {
        PageBean page = new PageBean();
        page.setPageSize(8);
        page.setCurrentPage(currentPage);
        ArticleCategory category = artileTypeProvider.getByCateName(cate_name);

        List<ArticleCategory> types = artileTypeProvider.getlist();
        Integer type_id = category.getId();
        List<Article> list = articleProvider.findPager(type_id, "1", page);
        page.setTotalCount(articleProvider.findCount(type_id, "1"));
        HashMap retMap = RetMap.Success("获取成功");
        retMap.put("list",list);

        return retMap;
    }


    @RequestMapping({ "/member/recharge" })

    public String money(String money,HttpServletRequest request) throws Exception {
        Member user = UserThreadLocal.get();
        List<IPlugin> plugins = paymentPluginBundle.getPluginList();

        for (IPlugin plugin : plugins) {
            if ("55".equals(plugin.getId())) {
                HashMap map = new HashMap();
                Auth auth = certificationProvider.findByUserId(user.getId());
                AccountBank bank = accountBankProvider.findByUserId(user.getId());
                if(auth == null)
                    return "尚未实名认证";
                if(bank ==null)
                    return "银行尚未认证";
                map.put("bank_card",bank.getBank_cardno());
                map.put("realname",auth.getReal_name());
                map.put("id_card_no",auth.getId_number());
                IPaymentEvent pay = (IPaymentEvent) plugin;
                return pay.onPay(user.getId(), new BigDecimal(money), map,request);
            }
        }
        return null;
    }


    @RequestMapping({ "/member/rechargeRz" })
    @ResponseBody
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "money", message = "充值金额不能为空")


    })
    public String rechargeRz(String money,HttpServletRequest request) throws Exception {
        Member user = UserThreadLocal.get();
        List<IPlugin> plugins = paymentPluginBundle.getPluginList();

        for (IPlugin plugin : plugins) {
            if ("57".equals(plugin.getId())) {
                HashMap map = new HashMap();
                Auth auth = certificationProvider.findByUserId(user.getId());
                AccountBank bank = accountBankProvider.findByUserId(user.getId());
                if(auth == null)
                    throw new NoticeException("尚未实名认证") ;
                if(bank ==null)
                    throw new NoticeException("银行尚未认证") ;
                map.put("bank_card",bank.getBank_cardno());
                map.put("realname",auth.getReal_name());
                map.put("id_card_no",auth.getId_number());
                IPaymentEvent pay = (IPaymentEvent) plugin;
                return pay.onPay(user.getId(), new BigDecimal(money), map,request);
            }
        }
        return JsonMapper.toJsonString(RetMap.Error("不存在的支付插件,请确保管理员已安装此种支付"));
    }


    @RequestMapping("/member/invite")
    @ResponseBody
    public HashMap link(
            HttpServletRequest request,
            HttpSession session,
            @RequestParam(value = "currentPage", required = false) Integer currentPage)
            throws Exception {
        Member loginUser =UserThreadLocal.get();
        // 查出该用户所有的推荐用户
        PageBean page = new PageBean();
        if (currentPage != null) {
            page.setCurrentPage(currentPage);
        }
        page.setPageSize(100);
        List userList = memberProvider.findPager(null,null,null,null,null,null,null,loginUser.getId()+"",null, null,page);
        int count = memberProvider.findCount(null,null,null,null,null,null,null,loginUser.getId()+"",null, null);
        HashMap retMap = RetMap.Success("获取成功");
        retMap.put("list",userList);

        return retMap;
    }

    /**
     * 银行卡列表
     */
    @RequestMapping(value = {"/banklist"},produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public HashMap bankSave(HttpServletRequest request, HttpSession session) throws Exception{
        HashMap retMap =  RetMap.Success("成功");
        retMap.put("list",fuyouProvider.getList());
        return retMap;
    }



    @RequestMapping({ "/index" })
    @ResponseBody
    public HashMap index(HttpServletRequest request, String mobileCode) {

        PageBean page = new PageBean();
        page.setPageSize(3);
        page.setCurrentPage(1);
        HashMap retMap =  RetMap.Success("成功");
        retMap.put("articles", articleProvider.findPager(1, "1", page));
        retMap.put("registers",memberProvider.countAllUser());
        retMap.put("totalTurnover",loanProvider.totalMoney()==null?"0":loanProvider.totalMoney().get("totalTurnover"));//累计投资
        //文章列表
        retMap.put("banners", advertProvider.getPPTList(1,2));
        PageBean borrowPage = new PageBean();
        borrowPage.setPageSize(3);

        retMap.put("loans",loanProvider.findPager(null,null,null,2,null,null,null,null,null,null,null,null,null,null,borrowPage));
        borrowPage.setPageSize(1);
        List<Map<String,Object>> rookie = loanProvider.findPager(null,null,null,1,3,null,null,null,null,null,null,null,null,null,page);
        if(rookie.size()==0)
        rookie = loanProvider.findPager(null,null,null,2,3,null,null,null,null,null,null,null,null,null,page);
        if(rookie.size()==0)
        rookie = loanProvider.findPager(null,null,null,1,5,null,null,null,null,null,null,null,null,null,page);
        if(rookie.size()==0)
        rookie = loanProvider.findPager(null,null,null,2,5,null,null,null,null,null,null,null,null,null,page);
        if(rookie.size()>0)
        retMap.put("rookie",rookie.get(0));
        return retMap;
    }


    @RequestMapping("/loginVerify")
    @ResponseBody
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "username", message = "用户名不能为空"),
            @RequiredStringValidator(fieldName = "password", message = "密码不能为空"),

    })
    public HashMap login(String username, String password,
                         HttpServletRequest request, HttpSession session) {



        if(StringUtils.isBlank(password)){
            throw new NoticeException("您的用户名或密码错误！");
        }

        Member user = memberProvider.findByUserNameOrMobilePhoneOrEmail(username.trim());

        if (user == null) {
            throw new NoticeException("您的用户名或密码错误！");
        }



        if (!StringUtils.equals(user.getLogin_password(), DigestUtils.md5Hex(password))) {
            throw new NoticeException("您的用户名或密码错误！");

        }
        session.setAttribute(Constants.PRINCIPAL_SESSION_NAME, user);
        user.setLast_ip(AppContext.getRemoteIp());
        user.setLast_time(MsDateUtils.getTime());
        user.setLogin_times(user.getLogin_times() + 1);
        memberProvider.updateById(user);
        HashMap retMap  =RetMap.Success("登录成功");;
        HashMap member =new HashMap();

        Auth auth = certificationProvider.findByUserId(user.getId());

        member.put("is_auth",auth==null?"0":"1");
        member.put("member_id",user.getId());
        member.put("mobile_status",user.getStatus());
        member.put("member_name",user.getUser_name());
        member.put("mobile",user.getMember_phone());
        retMap.put("member",member);

        return retMap;
    }
    /**
     * 验证码认证
     */

    @RequestMapping({ "/member/regcodeValidate" })
    @ResponseBody
    public HashMap register_confirm(HttpServletRequest request, String mobileCode) {
        Member user = UserThreadLocal.get();

        String mobileCodeSession =  applicationScope.getAttribute(user.getUser_name()).toString();
        if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
            throw new NoticeException("验证码错误或过期无效");
        }

        //验证码验证
        String[] codes = StringUtils.split(mobileCodeSession, "_");
        if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10 || StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], mobileCode) ){
            throw new NoticeException("验证码错误或过期无效");
        }
        user = memberProvider.findById(user.getId());
        user.setStatus(1);
        memberProvider.update(user);
        return RetMap.Success("验证成功");
    }





    /**
     * 验证手机号,获取验证码
     */
    @RequestMapping("/member/getRegCode")
    @ResponseBody
    public HashMap step_2_regcode(String mobile,  HttpServletResponse response) throws IOException, TemplateException {
        //发送校验



        Member user = memberProvider.findByMobilePhone(mobile);

        Object mobileCodeSession =  applicationScope.getAttribute(user.getUser_name());
        if(mobileCodeSession!=null){
            String session1 = mobileCodeSession.toString();
            String[] codes = StringUtils.split(session1, "_");
            if(System.currentTimeMillis() - Long.valueOf(codes[1]) < 1000*10*6){
                throw  new NoticeException("60秒内只能发送一条短信");
            }
        }
        if(user==null){
            throw  new NoticeException("用户不存在");

        }
        if(user.getStatus()==1){
            throw  new NoticeException("用户已认证");

        }


        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
        String mobileCode = CommonUtil.getRandomNum(6);
        String nickname = settingProvider.findByCode("email_from_name")
                .getText();
        String templatePath = Constants.TEMPLATE_SMS_BIND;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath, "utf-8");
        HashMap map = new HashMap();
        map.put("code",mobileCode);
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        // 发送短信
        smsService.sendSMS(mobile,"【"+nickname+"】"+content, "注册", 0);
        applicationScope.setAttribute(user.getUser_name(),mobileCode + "_" + System.currentTimeMillis());
        return RetMap.Success("发送短信成功");
    }
    /**
     * 注册
     */
    @Validations(requiredStrings = {

            @RequiredStringValidator(fieldName = "mobile", message = "手机号码不能正确"),
            @RequiredStringValidator(fieldName = "pass1", message = "密码不能为空")

    })
    @RequestMapping("/register")
    @ResponseBody
    public HashMap regist_step1( String pass1, String mobile, String inviter) {


        String username = mobile;

        if (pass1.equals(username)) {
            throw new NoticeException("用户名与密码不能相同！");
        }

        if (!(mobile.matches("^1[0-9]{10}$"))) {
            throw new NoticeException("请输入正确的手机号码！");
        }


        String pwdRegex = "^(.*){6,20}$";
        if (!pass1.matches(pwdRegex)) {
            throw new NoticeException("密码必须6-20位");
        }



        if (memberProvider.findByMobilePhone(mobile) != null) {
            throw new NoticeException("该手机号码已注册！");
        }

        Member member = new Member();
        if (inviter != null && !inviter.equals("")) {
            Member remmendUser = memberProvider.findByMobilePhone(inviter);
            if (remmendUser == null) {
                throw new NoticeException("推荐人手机号码不存在");
            }
            member.setLevel(remmendUser.getLevel() + 1);
            member.setFirst_recommend_id(remmendUser.getFirst_recommend_id() == 0 ? remmendUser.getId() : remmendUser.getFirst_recommend_id());
            member.setRecommend_id(remmendUser.getId());
        } else {
            member.setLevel(0);
            member.setFirst_recommend_id(0);
        }
        // 插入注册用户
        member.setUser_name(username.trim());
        member.setMember_phone(mobile);
        member.setLogin_password(DigestUtils.md5Hex(pass1));
        member.setPayment_password(DigestUtils.md5Hex(pass1));
        member.setStatus(0);
        member.setLogin_times(1);
        member.setAdd_ip(AppContext.getRemoteIp());
        member.setAdd_time(MsDateUtils.getTime());
        member.setUp_ip(member.getAdd_ip());
        member.setUp_time(member.getAdd_time());
        member.setLast_ip(member.getAdd_ip());
        member.setLast_time(member.getAdd_time());
        member = memberProvider.register(member);
        HashMap retMap = RetMap.Success("注册成功");
        HashMap user =new HashMap();
        user.put("member_id",member.getId());
        user.put("mobile_status",0);
        user.put("mobile",member.getMember_phone());
        user.put("member_name",member.getUser_name());
        retMap.put("member",user);
        return retMap;
    }


}
